<template>
  <div class="app-container">
    <el-card>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="医生信息" name="patients">
          <!-- 科室信息标签页的内容 -->
          <div class="app-container">
            <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch"
                     label-width="68px">
              <el-form-item label="根据名称" prop="isVerified">
                <el-input
                    v-model="queryParams.name"
                    clearable
                    @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
                <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
              <div class="form-right-area">
                <el-button :icon="Back" type="primary" plain @click="goBack">返回</el-button>
              </div>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    :icon="Plus"
                    @click="handleAdd"
                >新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    :icon="Delete"
                    @click="handleDelete"
                >删除
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"/>
            </el-row>

            <el-table v-loading="loading" :data="doctorsList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="医生编号" align="center" width="100" type="index"/>
              <el-table-column label="姓名" align="center" prop="name"/>
              <el-table-column label="性别" align="center" prop="gender">
                <template #default="{ row }">
                  {{ row.gender === 1 ? '男' : '女' }}
                </template>
              </el-table-column>
              <el-table-column label="电话号" align="center" prop="phone"/>
              <el-table-column label="职务" align="center" prop="title"/>
              <el-table-column label="问诊资金" align="center" prop="price"/>
              <el-table-column label="患者数量" align="center" prop="isVerified"/>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="{ row }">
                  <el-button
                      type="primary"
                      link
                      :icon="Edit"
                      @click="showAll(row)"
                  >查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                v-if="total > 0"
                v-model:current-page="queryParams.currentPage"
                v-model:page-size="queryParams.pageSize"
                :page-sizes="[1, 3, 10, 20]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />


            <el-dialog
                v-model="open"
                :title="title"
                width="500px"
                append-to-body
                :close-on-click-modal="false"
                :before-close="handleDialogClose"
            >
              <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="医生姓名" prop="name">
                  <el-input v-model="form.name" placeholder="请输入医生姓名"/>
                </el-form-item>
                <el-form-item label="医生头像" prop="imgurl">
                  <el-upload class="avatar-uploader" action="/api/doctor/upload" :show-file-list="false"
                             :headers="{ 'token': token }" :on-success="handleAvatarSuccess"
                             :before-upload="beforeAvatarUpload">
                    <el-image v-if="imageUrl" :src="imageUrl" class="avatar"/>
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus/>
                    </el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="form.gender">
                    <el-radio label="1">男</el-radio>
                    <el-radio label="2">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入联系电话"/>
                </el-form-item>
                <el-form-item label="问诊金额" prop="price">
                  <el-input-number v-model="form.price" :min="1" :max="1000">
                    <template #prefix>
                      <span>￥</span>
                    </template>
                  </el-input-number>
                </el-form-item>
                  <el-form-item label="所属医院">
                  <el-input v-model="route.params.hospitalName" disabled/>
                </el-form-item>
                <el-form-item label="科室" prop="departmentId">
                  <el-select v-model="form.departmentId" placeholder="请选择科室" disabled>
                    <el-option
                        :key="form.departmentId"
                        :label="departmentName"
                        :value="form.departmentId"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="职称" prop="title">
                  <el-select v-model="form.title" placeholder="请输入职称">
                    <el-option label="主任" value="主任"/>
                    <el-option label="副主任" value="副主任"/>
                    <el-option label="医师" value="医师"/>
                  </el-select>
                </el-form-item>
              </el-form>
              <template #footer>
                <div class="dialog-footer">
                  <el-button 
                    type="primary" 
                    @click="debouncedSubmitForm" 
                    :loading="submitLoading"
                    :disabled="submitLoading">
                    确 定
                  </el-button>
                  <el-button @click="cancel" :disabled="submitLoading">取 消</el-button>
                </div>
              </template>
            </el-dialog>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search, Refresh, Plus, Edit, Delete, Back} from '@element-plus/icons-vue'
import {delDoctors, addDoctors, updateDoctors, getBigdep, getHospition} from '../../api/doctors/doctors.js'
import {useRoute} from 'vue-router'
import {findDocByDepId} from "../../api/bigDep/bigDep.js";
import axios from "axios";
import router from "../../router/index.js";

const route = useRoute()
const activeTab = ref('patients')
// 添加token变量
const token = ref(localStorage.getItem("token"))
// 添加医院名称和科室名称
const hospitalName = ref(route.params.hospitalName || '')
const departmentName = ref(route.params.name || '')

// 遮罩层
const loading = ref(true)
// 添加提交按钮加载状态
const submitLoading = ref(false)
// 选中数组
const ids = ref([])
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 医生表格数据
const doctorsList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 表单ref
const formRef = ref()
// 查询表单ref
const queryFormRef = ref()

// 医院选项
const hospitalOptions = ref([])

function findHospitals() {
  axios({
    url: '/hospital/findHospitals',
    method: 'get',
  }).then((res) => {
    console.log('医院数据响应:', res.data);
    if (res.data && res.data.data) {
      hospitalOptions.value = res.data.data;
    } else {
      ElMessage.warning('获取医院列表数据格式异常');
    }
  }).catch(error => {
    console.error('获取医院列表失败:', error);
    ElMessage.error('获取医院列表失败');
  });
}

// 科室选项
const departmentOptions = ref([])

function findBigDeps() {
  axios({
    url: '/dep/findBigDeps',
    method: 'get',
  }).then((res) => {
    console.log('科室数据响应:', res.data);
    if (res.data && res.data.data) {
      departmentOptions.value = res.data.data;
    } else {
      ElMessage.warning('获取科室列表数据格式异常');
    }
  }).catch(error => {
    console.error('获取科室列表失败:', error);
    ElMessage.error('获取科室列表失败');
  });
}

// 查询参数
const queryParams = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  name: null,
  hospitalId: null,
  departmentId: route.params.id,
  queryString: null
})

// 选择查询条件
const selectQueryCondition = () => {
  if (queryParams.value.name) {
    queryParams.value.queryString = queryParams.value.name;
  } else {
    queryParams.value.queryString = null;
  }
};

// 表单参数
const form = reactive({
  id: null,
  name: '',
  gender: 0,
  phone: '',
  hospitalId: route.params.hospitalId || null,
  departmentId: route.params.id || null,
  price: null,
  title: '',
  imgurl: ''
})

// 表单校验规则
const rules = {
  name: [
    {required: true, message: '医生姓名不能为空', trigger: 'blur'}
  ],
  imgurl: [
    {required: true, message: '医生头像不能为空', trigger: 'change'}
  ],
  gender: [
    {required: true, message: '性别不能为空', trigger: 'change'}
  ],
  phone: [
    {required: true, message: '联系电话不能为空', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
  price: [
    {required: true, message: '问诊金额不能为空', trigger: 'blur'},
    {type: 'number', min: 1, max: 1000, message: '问诊金额必须在1-1000元之间', trigger: 'blur'}
  ],
  hospitalId: [
    {required: true, message: '请选择所属医院', trigger: 'change'}
  ],
  departmentId: [
    {required: true, message: '请选择科室', trigger: 'change'}
  ],
  title: [
    {required: true, message: '职称不能为空', trigger: 'change'}
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 查询医生列表
const getList = async () => {
  selectQueryCondition()
  loading.value = true
  try {
    const res = await findDocByDepId(queryParams.value)
    doctorsList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 表单重置
const reset = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: null,
    name: '',
    gender: 0,
    phone: '',
    hospitalId: route.params.hospitalId || null,
    departmentId: route.params.id || null,
    price: null,
    title: '',
    imgurl: ''
  })
  // 重置图片
  imageUrl.value = '';
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.value.name = null
  queryParams.value.queryString = null
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = async () => {
  reset()
  // 设置医院和科室的ID
  form.hospitalId = route.params.hospitalId || null
  form.departmentId = route.params.id || null
  open.value = true
  title.value = '添加医生'
}

/**
 * 查看详情
 */
const showAll = (row) => {
  console.log('准备跳转到医生详情页，数据:', row)
  console.log('route.params:', route.params)
  
  // 确保传递正确的id
  if (!row.id) {
    ElMessage.error('医生ID不能为空')
    return
  }
  
  // 使用path路径参数，避免params不生效的问题
  const targetPath = `/showDepDocAll/${row.id}/${encodeURIComponent(route.params.name || '')}/${encodeURIComponent(route.params.hospitalName || '')}`
  
  // 构建查询参数
  const query = {
    from: 'showDepDocAll',
    departmentId: route.params.id || '',
    hospitalId: route.params.hospitalId || '',
    hospitalName: route.params.hospitalName || '',
    departmentName: route.params.name || ''
  }
  
  console.log('即将跳转到路径:', targetPath)
  console.log('即将传递的query:', query)
  
  router.push({
    path: targetPath,
    query: query
  })
}

// 添加防抖函数
function debounce(fn, delay = 300) {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
}

// 提交按钮
const submitForm = async () => {
  await formRef.value?.validate()
  try {
    // 防止重复提交
    if (submitLoading.value) {
      return;
    }
    
    // 设置提交状态为加载中
    submitLoading.value = true;
    
    if (form.id) {
      await updateDoctors(form)
      ElMessage.success('修改成功')
    } else {
      await addDoctors(form)
      ElMessage.success('新增成功')
    }
    open.value = false
    getList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    // 延迟重置提交状态，确保按钮禁用效果明显
    setTimeout(() => {
      submitLoading.value = false;
    }, 500);
  }
}

// 使用防抖包装提交函数
const debouncedSubmitForm = debounce(submitForm, 300);

// 删除按钮操作
const handleDelete = async (row) => {
  const deleteIds = row?.id || ids.value
  if (!deleteIds || (Array.isArray(deleteIds) && deleteIds.length === 0)) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  try {
    await ElMessageBox.confirm('是否确认删除选中的数据项？')
    if (Array.isArray(deleteIds)) {
      // 批量删除
      const deletePromises = deleteIds.map(id => delDoctors(id))
      await Promise.all(deletePromises)
    } else {
      // 单个删除
      await delDoctors(deleteIds)
    }
    await getList()
    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除失败:', error)
  }
}
/**
 * 图片上传
 */
// const formRef = ref()
const imageUrl = ref('')
const handleAvatarSuccess = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  form.imgurl = response.data
  console.log(response.data);
}
//验证的函数
const beforeAvatarUpload = (rawFile) => {
  const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type === 'image/jpg';
  if (!isImage) {
    ElMessage.error('Avatar picture must be in JPG, PNG, or JPEG format!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size cannot exceed 2MB!');
    return false;
  }
  return true;
};

// 取消按钮
const cancel = () => {
  // 如果正在提交中，不允许关闭
  if (submitLoading.value) {
    return;
  }
  open.value = false
  reset()
}

// 对话框关闭处理函数
const handleDialogClose = (done) => {
  if (submitLoading.value) {
    ElMessage.warning('正在提交数据，请稍后...');
    return;
  }
  
  // 重置表单
  formRef.value?.resetFields();
  // 重置数据
  reset();
  // 确保提交按钮状态重置
  submitLoading.value = false;
  
  done();
};

/**
 * 分页
 */
// 添加分页处理方法
// 页面大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val.data
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val.data
  getList()
}

// 返回按钮处理函数
const goBack = () => {
  router.push({
    name: 'listDepartment',
    params: {
      id: route.params.hospitalId,
      name: route.params.hospitalName
    }
  });
}

onMounted(() => {
  getList()
  // 初始化时获取医院和科室数据
  findHospitals()
  findBigDeps()
})


</script>

<style scoped>
.app-container {
  padding: 20px;
}

.doctor-info {
  display: flex;
  gap: 40px;
  padding: 20px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.avatar-container {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-form {
  flex: 1;
}

.doctor-form {
  max-width: 600px;
}

.qr-code {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.qr-label {
  font-size: 14px;
  color: #606266;
}

.qr-image {
  width: 150px;
  height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.qr {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

:deep(.el-tabs__nav) {
  background-color: #fff;
  padding: 0 20px;
}

.form-right-area {
  margin-left: auto;
  display: flex;
  align-items: center;
  position: absolute;
  right: 20px;
  top: 0;
}
</style>
